<script setup>
import IconSimple from '@/components/icon-simple/index.vue'
import {isNaN} from 'lodash'

const props = defineProps({
  modelValue: Number,
  min: {
    type: Number,
    default: 0
  },
  max: {
    type: Number,
    default: 9999
  },
  defaultVal: {
    type: Number,
    default: 0
  },
  focus: Boolean,
})

const emit = defineEmits(['blur', 'update:modelValue'])

const val = ref(props.modelValue || props.defaultVal)
const focus = ref(props.focus || false)
const trigger = ref(false)

watch(props, (newVal) => {
  if (newVal.focus !== focus.value) {
    focus.value = props.focus
  }
})

const blur = (e) => {
  // focus.value = false
  // trigger.value = false
  emit('blur', e)
}
const inputActive = () => {
  focus.value = true
  trigger.value = true
}

const minus = () => {
  const result = val.value - 1
  if (result < props.min) {
    val.value = props.min
  } else {
    val.value = result
  }
}
const plus = () => {
  const result = val.value + 1
  if (result > props.max) {
    val.value = props.max
  } else {
    val.value = result
  }
}

const input = ({ detail: { value } }) => {
  const newVal = isNaN(parseInt(value)) ? props.defaultVal : parseInt(value)
  if (newVal < props.min) {
    val.value = props.min
  } else if (newVal > props.max) {
    val.value = props.max
  } else {
    val.value = newVal
  }
}

const minusDisable = computed(() => val.value <= props.min)
const plusDisable = computed(() => val.value >= props.max)

watch(val, newVal => emit('update:modelValue', newVal))

</script>

<template>
  <view class="number-box-container" @click.prevent>
    <view class="minus-icon-container" :class="{ 'minus-icon-disabled': minusDisable }" @click.prevent="minus" >
      <icon-simple name="minus" />
    </view>
    <view class="context-container">
      <input v-if="trigger" type="number" class="context-input-bar" :focus="focus" :value="val" @input="input" @blur="blur" />
      <view class="context-text" :style="{ opacity: trigger ? 0 : 1 }" @click="inputActive">{{ val }}</view>
    </view>
    <view class="plus-icon-container" :class="{ 'plus-icon-disabled': plusDisable }" @click.prevent="plus" >
      <icon-simple name="add" />
    </view>
  </view>
</template>

<style scoped lang="scss">
.number-box-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 0;
}
.minus-icon-container, .plus-icon-container {
  padding: 0 8rpx;
}
.context-container {
  box-sizing: border-box;
  position: relative;
}
.context-input-bar, .context-text {
  min-width: 84rpx;
  @include fs36w600;
  border-radius: 16rpx;
  background-color: $kaoyan-color-13;
  overflow: hidden;
}
.context-input-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 50rpx;
}
.minus-icon-disabled,
.plus-icon-disabled {
  opacity: .5;
}
</style>
